package com.example.musicrecommend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.musicrecommend.common.BaseResponse;
import com.example.musicrecommend.common.ErrorCode;
import com.example.musicrecommend.common.ResultUtils;
import com.example.musicrecommend.exception.BusinessException;
import com.example.musicrecommend.exception.ThrowUtils;
import com.example.musicrecommend.model.dto.collect.CollectAddRequest;
import com.example.musicrecommend.model.dto.collect.CollectQueryRequest;
import com.example.musicrecommend.model.entity.Collect;
import com.example.musicrecommend.model.vo.SongVO;
import com.example.musicrecommend.service.CollectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("/collect")
@Slf4j
public class CollectController {


    @Resource
    private CollectService collectService;

    /**
     * 是否收藏
     */
    @PostMapping("/check")
    public BaseResponse<Boolean> checkCollectState(@RequestBody CollectAddRequest collectAddRequest,HttpServletRequest request) {
        if(collectAddRequest == null )
        {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Collect collect = new Collect();
        BeanUtils.copyProperties(collectAddRequest,collect);
        // 校验
        collectService.validCollect(collect,false);

        long userId = collect.getUserId();
        long songId = collect.getSongId();
        QueryWrapper<Collect> wrapper = new QueryWrapper<>();
        wrapper.eq(userId>0,"userId",userId);
        wrapper.eq(songId>0,"songId",songId);

        long count = collectService.count(wrapper);
        return ResultUtils.success(count>0);
    }

    /**
     * 添加收藏
     * @param collectAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addCollect(@RequestBody CollectAddRequest collectAddRequest, HttpServletRequest request) {
        if(collectAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Collect collect = new Collect();
        BeanUtils.copyProperties(collectAddRequest,collect);

        // 校验
        collectService.validCollect(collect,false);

        long userId = collect.getUserId();
        long songId = collect.getSongId();
        QueryWrapper<Collect> wrapper = new QueryWrapper<>();
        wrapper.eq(userId>0,"userId",userId);
        wrapper.eq(songId>0,"songId",songId);

        Collect existingCollect = collectService.selectOneIncludeDeleted(wrapper);

        if(existingCollect !=null) {
            //存在 且已删除
            if(existingCollect.getIsDelete() == 1) {
                existingCollect.setIsDelete(0);

                boolean result = collectService.updateCollectById(existingCollect.getId(),existingCollect);
                ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR);
                return ResultUtils.success(existingCollect.getId());
            }
            //存在 且 未删除s
            else {
                throw  new BusinessException(ErrorCode.FORBIDDEN_ERROR,"该歌曲已收藏");
            }
        }
        else {
            //不存在
            boolean result = collectService.save(collect);
            ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR);
            return ResultUtils.success(collect.getId());

        }
    }

    /**
     * 取消收藏
     * @param collectAddRequest
     * @param request
     * @return
     */
    @PostMapping("/del")
    public BaseResponse<Boolean> delCollect(@RequestBody CollectAddRequest collectAddRequest, HttpServletRequest request) {
        if(collectAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Collect collect = new Collect();
        BeanUtils.copyProperties(collectAddRequest,collect);

        // 校验
        collectService.validCollect(collect,false);

        long userId = collect.getUserId();
        long songId = collect.getSongId();
        QueryWrapper<Collect> wrapper = new QueryWrapper<>();
        wrapper.eq(userId>0,"userId",userId);
        wrapper.eq(songId>0,"songId",songId);

        Collect existingCollect = collectService.getOne(wrapper);

        ThrowUtils.throwIf(existingCollect ==null,ErrorCode.OPERATION_ERROR,"该歌曲已是未收藏");

        boolean result = collectService.removeById(existingCollect.getId());
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR,"取消收藏失败");
        return ResultUtils.success(true);
    }



    /**
     * 分页获取collectSong列表
     *
     * @param collectQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<SongVO>> listCollectSongPageByUserId(CollectQueryRequest collectQueryRequest,
                                                     HttpServletRequest request) {

        long current = collectQueryRequest.getCurrent();
        long size = collectQueryRequest.getPageSize();
        Page<SongVO> songPage =collectService.selectCollectSongsPage(new Page<>(current, size),
                collectQueryRequest.getUserId());

        return ResultUtils.success(songPage);
    }


}


